package handler.message;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import protocol.packet.message.MessageRequest;
import protocol.packet.message.MessageResponse;
import session.Session;
import utils.SessionUtil;

import java.util.Date;

public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequest request) throws Exception {
        // 消息处理
        System.out.println(new Date() + ": 收到客户端消息-->"+ request.getMsg());
        // 获取发送方消息的会话信息
        Session session = SessionUtil.getSession(ctx.channel());
        MessageResponse response = new MessageResponse();
        response.setFromUserId(session.getUserId());
        response.setFromUserName(session.getUserName());
        response.setMsg(request.getMsg());

        Channel toUserChannel = SessionUtil.getChannel(request.getToUserId());
        if(toUserChannel != null && SessionUtil.hasLogin(toUserChannel)) {
            toUserChannel.writeAndFlush(response);
        } else {
            System.out.println("[ " + request.getToUserId() + " ] 不在线，发送失败!");
        }
    }
}
